package com.pay.cloud.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.pay.cloud.KeyInfo;
import com.pay.cloud.R;
import com.pay.cloud.SubScreenFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;


public class PayExpressionFragment extends Fragment {
    private View view;
    // 算式
    private StringBuffer expression = new StringBuffer();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_pay_expression, container, false);
        SubScreenFactory.startSubScreenToWelcome(getContext());
        showExpression();
        return view;
    }

    public String statAmount(KeyInfo keyInfo) {
        if (null != keyInfo.getValue()) {
            expression.append(keyInfo.getValue());
        } else if (keyInfo == KeyInfo.KEY_CANCEL && expression.length() > 0) {
            expression = new StringBuffer();
        } else if (keyInfo == KeyInfo.KEY_DELETE && expression.length() > 0) {
            int i = expression.lastIndexOf("+");
            if (i != -1) {
                expression.delete(expression.lastIndexOf("+"), expression.length());
            } else {
                expression = new StringBuffer();
            }
        }
        showExpression();
        return statAmount();
    }

    private void showExpression() {
        if (null != view) {
            TextView expressionView = view.findViewById(R.id.expression);
            expressionView.setText(expression.toString());
        }
    }

    private String statAmount() {
        String[] items = expression.toString().split("\\+");
        BigDecimal amount = BigDecimal.ZERO;
        for (String item : items) {
            if (null != item && !item.trim().equals("")) {
                try {
                    amount = amount.add(new BigDecimal(item));
                } catch(NumberFormatException e) {}
            }
        }
        return amount.setScale(2, RoundingMode.DOWN).toPlainString();
    }
}
